import copy
import os

from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView
from SecureHelperServer.settings import formatResponseData, MEDIA_ROOT, MEDIA_URL
from utils.conf import Response, newID
from utils.custom import MyJWTAuthentication


class UploadVideoView(APIView):
    # 局部(本视图有效)认证类
    authentication_classes = [MyJWTAuthentication]
    # 局部(本视图有效)权限类
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        """
        note上传视频
        """
        data = copy.deepcopy(formatResponseData)
        try:
            videoFile = request.FILES.get("videoFile")

            if not videoFile:
                return Response(data=data, responseMsg="请求参数缺失", loggerMsg="请求参数缺失", isError=True)

            video = videoFile.read()
            videoType = videoFile.name.split(".")[-1]
            videoName = f"{request.user.uid}_{newID()}.{videoType}"
            uploadPath = os.path.join(MEDIA_ROOT, "userNotesMedia", "userNotesVideos", videoName)
            with open(uploadPath, 'wb') as f:
                f.write(video)

            url = os.path.join(f'{MEDIA_URL}', "userNotesMedia", "userNotesVideos", videoName)
            data["data"]["url"] = url

            return Response(data=data, loggerMsg=f"note上传视频：成功，videoName={videoName}")

        except Exception as e:
            return Response(data=data, responseMsg="视频上传失败",
                            loggerMsg=f"请求处理失败: {e}", isError=True)
